<template>
  <a-space align="center" style="margin-bottom:16px; width:100%; justify-content:center;">
    <a-form :model="formSearch" layout="inline" @submit="doSearch">
      <a-form-item field="title" label="标题">
        <a-input v-model="formSearch.title" placeholder="请输入标题" allow-clear />
      </a-form-item>
      <a-form-item field="content" label="内容">
        <a-input v-model="formSearch.content" placeholder="请输入内容关键字" allow-clear />
      </a-form-item>
      <a-form-item field="userId" label="用户 ID">
        <a-input v-model="formSearch.userId" placeholder="请输入用户 ID" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-popover trigger="click" title="列设置">
            <template #content>
              <a-checkbox-group v-model="selectedKeys" :options="columnOptions" />
            </template>
            <a-button>列设置</a-button>
          </a-popover>
          <a-button type="primary" @click="openModal('add')">新增帖子</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-space>

  <a-table
    :columns="visibleColumns"
    :data="dataList"
    :pagination="{ showTotal:true, pageSize:searchParams.pageSize, current:searchParams.current, total }"
    @page-change="onPageChange"
  >
    <template #tags="{ record }">
      <a-tag v-for="tag in record.tagList||[]" :key="tag">{{ tag }}</a-tag>
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm') }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm') }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button type="text" @click="openModal('edit', record)">编辑</a-button>
        <a-button status="danger" @click="doDelete(record)">删除</a-button>
      </a-space>
    </template>
  </a-table>

  <a-modal
    v-model:visible="modalVisible"
    :title="modalType==='add'?'新增帖子':'编辑帖子'"
    @ok="handleModalOk"
    :confirm-loading="modalLoading"
  >
    <a-form :model="modalForm" label-align="left" auto-label-width>
      <a-form-item field="title" label="标题" :required="true">
        <a-input v-model="modalForm.title" />
      </a-form-item>
      <a-form-item field="content" label="内容" :required="true">
        <a-textarea v-model="modalForm.content" rows="4" />
      </a-form-item>
      <a-form-item field="tagsInput" label="标签(逗号分隔)">
        <a-input v-model="modalForm.tagsInput" placeholder="例如：vue,javascript,前端" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect, computed } from 'vue';
import dayjs from 'dayjs';
import type { CheckboxOption } from '@arco-design/web-vue';
import {
  listPostVoByPageUsingPost,
  addPostUsingPost,
  editPostUsingPost,
  deletePostUsingPost
} from '@/api/postController';
import API from '@/api';
import message from '@arco-design/web-vue/es/message';

// --- 列配置 ---
interface ColDef { key:string; title:string; dataIndex?:string; slotName?:string }
const allColumns: ColDef[] = [
  { key:'id',           title:'ID',            dataIndex:'id' },
  { key:'title',        title:'标题',          dataIndex:'title' },
  { key:'content',      title:'内容',          dataIndex:'content' },
  { key:'tags',         title:'标签',          slotName:'tags' },
  { key:'favourNum',    title:'收藏数',        dataIndex:'favourNum' },
  { key:'thumbNum',     title:'点赞数',        dataIndex:'thumbNum' },
  { key:'userId',       title:'用户 ID',       dataIndex:'userId' },
  { key:'createTime',   title:'创建时间',      dataIndex:'createTime', slotName:'createTime' },
  { key:'updateTime',   title:'更新时间',      dataIndex:'updateTime', slotName:'updateTime' },
  { key:'optional',     title:'操作',          slotName:'optional' },
];
const defaultKeys = ['title','content','tags','createTime','optional'];
const selectedKeys = ref<string[]>([...defaultKeys]);
const columnOptions = computed<CheckboxOption[]>(()=>
  allColumns.map(c=>({ label:c.title, value:c.key }))
);
const visibleColumns = computed(()=>
  allColumns.filter(c=>selectedKeys.value.includes(c.key))
    .map(c=>{ const col:any={ title:c.title, key:c.key }; if(c.dataIndex)col.dataIndex=c.dataIndex; if(c.slotName)col.slotName=c.slotName; return col })
);

// --- 数据 & 搜索 & 分页 ---
const formSearch = ref<Partial<API.PostQueryRequest>>({});
const initSearch = { current:1, pageSize:10 };
const searchParams = ref<Partial<API.PostQueryRequest>>({...initSearch});
const dataList = ref<API.PostVO[]>([]);
const total = ref(0);
async function loadData(){
  const res = await listPostVoByPageUsingPost(searchParams.value);
  if(res.data.code===0){
    dataList.value=res.data.data?.records||[];
    total.value=res.data.data?.total||0;
  } else message.error('获取失败：'+res.data.message);
}
function doSearch(){
  searchParams.value={ ...initSearch, ...formSearch.value };
}
function onPageChange(page:number){
  searchParams.value={ ...searchParams.value, current:page };
}
async function doDelete(rec:API.PostVO){
  if(!rec.id) return;
  const res=await deletePostUsingPost({ id:rec.id });
  if(res.data.code===0){ message.success('删除成功'); loadData(); }
  else message.error('删除失败：'+res.data.message);
}
watchEffect(loadData);

// --- 新增/编辑模态 ---
const modalVisible=ref(false);
const modalLoading=ref(false);
const modalType=ref<'add'|'edit'>('add');
const modalForm=reactive({
  id:undefined as number|undefined,
  title:'',
  content:'',
  tagsInput:'' as string
});
function openModal(type:'add'|'edit', rec?:API.PostVO){
  modalType.value=type;
  if(type==='edit'&&rec){
    modalForm.id=rec.id;
    modalForm.title=rec.title||'';
    modalForm.content=rec.content||'';
    modalForm.tagsInput=(rec.tagList||[]).join(',');
  } else {
    modalForm.id=undefined;
    modalForm.title='';
    modalForm.content='';
    modalForm.tagsInput='';
  }
  modalVisible.value=true;
}
async function handleModalOk(){
  modalLoading.value=true;
  try {
    const payload:any={
      title:modalForm.title,
      content:modalForm.content,
      tags: modalForm.tagsInput
        .split(',')
        .map(s=>s.trim())
        .filter(s=>s)
    };
    if(modalType.value==='edit'){
      payload.id=modalForm.id;
      await editPostUsingPost(payload);
      message.success('编辑成功');
    } else {
      await addPostUsingPost(payload);
      message.success('新增成功');
    }
    modalVisible.value=false;
    loadData();
  } catch(e:any){
    message.error('操作失败：'+e.message);
  } finally {
    modalLoading.value=false;
  }
}
</script>
